// 全局变量
let currentWeatherData = null;
let forecastData = null;
let aqiData = null;
let trendChart = null;
let aqiChart = null;
let isNightMode = false;

// API配置
const API_KEY = 'YOUR_API_KEY'; // 替换为你的OpenWeatherMap API密钥
const API_BASE_URL = 'https://api.openweathermap.org/data/3.0';
const GEOCODING_URL = 'https://api.openweathermap.org/geo/1.0';

// DOM元素
const locationSearch = document.getElementById('location-search');
const searchBtn = document.getElementById('search-btn');
const locationBtn = document.getElementById('location-btn');
const themeToggle = document.getElementById('theme-toggle');
const loadingModal = document.getElementById('loading-modal');
const lastUpdateEl = document.getElementById('last-update');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 默认加载北京的天气
    getWeatherByCity('北京');
    
    // 事件监听器
    searchBtn.addEventListener('click', () => {
        const city = locationSearch.value.trim();
        if (city) {
            getWeatherByCity(city);
        }
    });
    
    locationSearch.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            const city = locationSearch.value.trim();
            if (city) {
                getWeatherByCity(city);
            }
        }
    });
    
    locationBtn.addEventListener('click', getCurrentLocationWeather);
    
    themeToggle.addEventListener('click', toggleNightMode);
    
    // 趋势图按钮切换
    document.querySelector('.temp-trend-btn').addEventListener('click', () => {
        updateTrendChart('temp');
        document.querySelector('.temp-trend-btn').classList.remove('bg-gray-100', 'text-gray-600');
        document.querySelector('.temp-trend-btn').classList.add('bg-primary', 'text-white');
        document.querySelector('.precip-trend-btn').classList.remove('bg-primary', 'text-white');
        document.querySelector('.precip-trend-btn').classList.add('bg-gray-100', 'text-gray-600');
        document.querySelector('.wind-trend-btn').classList.remove('bg-primary', 'text-white');
        document.querySelector('.wind-trend-btn').classList.add('bg-gray-100', 'text-gray-600');
    });
    
    document.querySelector('.precip-trend-btn').addEventListener('click', () => {
        updateTrendChart('precipitation');
        document.querySelector('.precip-trend-btn').classList.remove('bg-gray-100', 'text-gray-600');
        document.querySelector('.precip-trend-btn').classList.add('bg-primary', 'text-white');
        document.querySelector('.temp-trend-btn').classList.remove('bg-primary', 'text-white');
        document.querySelector('.temp-trend-btn').classList.add('bg-gray-100', 'text-gray-600');
        document.querySelector('.wind-trend-btn').classList.remove('bg-primary', 'text-white');
        document.querySelector('.wind-trend-btn').classList.add('bg-gray-100', 'text-gray-600');
    });
    
    document.querySelector('.wind-trend-btn').addEventListener('click', () => {
        updateTrendChart('wind');
        document.querySelector('.wind-trend-btn').classList.remove('bg-gray-100', 'text-gray-600');
        document.querySelector('.wind-trend-btn').classList.add('bg-primary', 'text-white');
        document.querySelector('.temp-trend-btn').classList.remove('bg-primary', 'text-white');
        document.querySelector('.temp-trend-btn').classList.add('bg-gray-100', 'text-gray-600');
        document.querySelector('.precip-trend-btn').classList.remove('bg-primary', 'text-white');
        document.querySelector('.precip-trend-btn').classList.add('bg-gray-100', 'text-gray-600');
    });
});

// 获取当前位置的天气
function getCurrentLocationWeather() {
    if (navigator.geolocation) {
        showLoading();
        navigator.geolocation.getCurrentPosition(
            (position) => {
                const { latitude, longitude } = position.coords;
                getWeatherByCoords(latitude, longitude);
            },
            (error) => {
                hideLoading();
                alert('无法获取你的位置。请手动搜索城市。');
                console.error('Geolocation error:', error);
            }
        );
    } else {
        alert('你的浏览器不支持地理位置服务。请手动搜索城市。');
    }
}

// 通过城市名称获取天气
async function getWeatherByCity(city) {
    showLoading();
    try {
        // 获取城市坐标
        const geoResponse = await axios.get(`${GEOCODING_URL}/direct`, {
            params: {
                q: city,
                limit: 1,
                appid: API_KEY
            }
        });
        
        if (!geoResponse.data || geoResponse.data.length === 0) {
            hideLoading();
            alert('未找到该城市，请尝试其他城市名称。');
            return;
        }
        
        const { lat, lon, name, country } = geoResponse.data[0];
        getWeatherByCoords(lat, lon, `${name}, ${country}`);
    } catch (error) {
        hideLoading();
        console.error('Error fetching weather:', error);
        alert('获取天气数据失败，请稍后再试。');
    }
}

// 通过坐标获取天气
async function getWeatherByCoords(lat, lon, locationName = null) {
    try {
        // 获取当前天气
        const currentWeatherResponse = await axios.get(`${API_BASE_URL}/onecall`, {
            params: {
                lat,
                lon,
                exclude: 'minutely',
                appid: API_KEY,
                units: 'metric',
                lang: 'zh_cn'
            }
        });
        
        currentWeatherData = currentWeatherResponse.data;
        forecastData = currentWeatherResponse.data.daily;
        aqiData = currentWeatherResponse.data.current.aqi;
        
        // 更新UI
        updateCurrentWeatherUI(locationName);
        updateHourlyForecastUI();
        updateDailyForecastUI();
        updateSunriseSunsetUI();
        updateAQIUI();
        createTrendChart();
        updateWeatherAlert();
        updateLastUpdateTime();
        
        hideLoading();
    } catch (error) {
        hideLoading();
        console.error('Error fetching weather:', error);
        alert('获取天气数据失败，请稍后再试。');
    }
}

// 更新当前天气UI
function updateCurrentWeatherUI(locationName) {
    if (!currentWeatherData) return;
    
    const { current } = currentWeatherData;
    
    // 更新位置名称
    if (locationName) {
        document.getElementById('location-name').textContent = locationName;
    }
    
    // 更新温度
    document.getElementById('current-temp').textContent = `${Math.round(current.temp)}°`;
    document.getElementById('feels-like').textContent = `体感温度: ${Math.round(current.feels_like)}°`;
    
    // 更新温度范围
    const minTemp = Math.round(Math.min(...forecastData.map(day => day.temp.min)));
    const maxTemp = Math.round(Math.max(...forecastData.map(day => day.temp.max)));
    document.getElementById('temp-range').textContent = `${minTemp}° ~ ${maxTemp}°`;
    
    // 更新天气图标和描述
    const weatherIcon = document.getElementById('weather-icon');
    const weatherDescription = document.getElementById('weather-description');
    
    const weatherCode = current.weather[0].id;
    const weatherMain = current.weather[0].main;
    
    weatherDescription.textContent = current.weather[0].description;
    weatherIcon.textContent = getWeatherIcon(weatherCode, currentWeatherData.current.dt, 
                                            currentWeatherData.current.sunrise, 
                                            currentWeatherData.current.sunset);
    
    // 更新其他天气参数
    document.getElementById('humidity').textContent = `${current.humidity}%`;
    document.getElementById('wind-speed').textContent = `${(current.wind_speed * 3.6).toFixed(1)} km/h`;
    document.getElementById('uv-index').textContent = `${current.uvi} (${getUVIndexDescription(current.uvi)})`;
    document.getElementById('cloud-cover').textContent = `${current.clouds}%`;
    document.getElementById('pressure').textContent = `${current.pressure} hPa`;
    document.getElementById('visibility').textContent = `${(current.visibility / 1000).toFixed(1)} km`;
}

// 更新小时预报UI
function updateHourlyForecastUI() {
    if (!currentWeatherData) return;
    
    const hourlyForecastContainer = document.getElementById('hourly-forecast');
    hourlyForecastContainer.innerHTML = '';
    
    // 只显示未来24小时
    const hourlyData = currentWeatherData.hourly.slice(0, 24);
    
    hourlyData.forEach(hour => {
        const date = new Date(hour.dt * 1000);
        const hourText = date.getHours().toString().padStart(2, '0');
        
        const hourElement = document.createElement('div');
        hourElement.className = 'bg-white/80 rounded-xl p-4 text-center min-w-[80px] transition-all duration-300 hover:bg-white';
        
        hourElement.innerHTML = `
            <p class="text-sm text-gray-500 mb-2">${hourText}时</p>
            <div class="text-2xl mb-2">${getWeatherIcon(hour.weather[0].id, hour.dt, 
                                                        currentWeatherData.current.sunrise, 
                                                        currentWeatherData.current.sunset)}</div>
            <p class="font-semibold">${Math.round(hour.temp)}°</p>
            <p class="text-xs text-gray-500 mt-1">${hour.pop * 100}%</p>
        `;
        
        hourlyForecastContainer.appendChild(hourElement);
    });
}

// 更新未来7天预报UI
function updateDailyForecastUI() {
    if (!forecastData) return;
    
    const dailyForecastContainer = document.getElementById('daily-forecast');
    dailyForecastContainer.innerHTML = '';
    
    // 跳过今天，显示未来7天
    const dailyData = forecastData.slice(1, 8);
    
    dailyData.forEach(day => {
        const date = new Date(day.dt * 1000);
        const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        const weekday = weekdays[date.getDay()];
        
        const dayElement = document.createElement('div');
        dayElement.className = 'flex items-center justify-between bg-white/80 rounded-lg p-3 transition-all duration-300 hover:bg-white';
        
        dayElement.innerHTML = `
            <div class="flex items-center">
                <span class="font-medium mr-4">${weekday}</span>
                <span class="text-xl">${getWeatherIcon(day.weather[0].id, day.dt, 
                                                      currentWeatherData.current.sunrise, 
                                                      currentWeatherData.current.sunset)}</span>
            </div>
            <div class="flex items-center">
                <span class="font-semibold mr-3">${Math.round(day.temp.max)}°</span>
                <span class="text-gray-500">${Math.round(day.temp.min)}°</span>
                <span class="ml-4 text-xs text-gray-500">${day.pop * 100}%</span>
            </div>
        `;
        
        dailyForecastContainer.appendChild(dayElement);
    });
}

// 更新日出日落UI
function updateSunriseSunsetUI() {
    if (!currentWeatherData) return;
    
    const { current } = currentWeatherData;
    const sunriseTime = new Date(current.sunrise * 1000);
    const sunsetTime = new Date(current.sunset * 1000);
    const currentTime = new Date(current.dt * 1000);
    
    // 更新时间显示
    document.getElementById('sunrise-time').textContent = `${sunriseTime.getHours().toString().padStart(2, '0')}:${sunriseTime.getMinutes().toString().padStart(2, '0')}`;
    document.getElementById('sunset-time').textContent = `${sunsetTime.getHours().toString().padStart(2, '0')}:${sunsetTime.getMinutes().toString().padStart(2, '0')}`;
    
    // 计算太阳位置
    const totalDaylightSeconds = sunsetTime - sunriseTime;
    const secondsSinceSunrise = currentTime - sunriseTime;
    
    let sunPositionPercentage = 0;
    let isNight = false;
    
    if (secondsSinceSunrise < 0) {
        // 日出前
        isNight = true;
        sunPositionPercentage = 0;
    } else if (secondsSinceSunrise > totalDaylightSeconds) {
        // 日落后
        isNight = true;
        sunPositionPercentage = 100;
    } else {
        // 白天
        sunPositionPercentage = (secondsSinceSunrise / totalDaylightSeconds) * 100;
    }
    
    // 更新太阳路径
    const sun = document.getElementById('sun');
    const moon = document.getElementById('moon');
    const sunPath = document.getElementById('sun-path');
    
    // 计算太阳高度（抛物线）
    const heightPercentage = -4 * (sunPositionPercentage / 100 - 0.5) ** 2 + 1;
    const height = heightPercentage * 70; // 70% of the container height
    
    // 设置太阳/月亮位置
    sun.style.left = `${sunPositionPercentage}%`;
    sun.style.bottom = `${height}%`;
    moon.style.left = `${sunPositionPercentage}%`;
    moon.style.bottom = `${height}%`;
    
    // 显示/隐藏太阳和月亮
    if (isNight) {
        sun.classList.add('hidden');
        moon.classList.remove('hidden');
    } else {
        sun.classList.remove('hidden');
        moon.classList.add('hidden');
    }
}

// 更新空气质量UI
function updateAQIUI() {
    if (!aqiData) return;
    
    const aqiValue = document.getElementById('aqi-value');
    const aqiStatus = document.getElementById('aqi-status');
    const aqiIconContainer = document.querySelector('.w-24.h-24.rounded-full.bg-success\\/20');
    const aqiIcon = document.querySelector('.fa-leaf');
    
    aqiValue.textContent = aqiData;
    
    let statusText, statusColor, iconColor, bgColor;
    
    switch (aqiData) {
        case 1:
            statusText = '优';
            statusColor = 'text-success';
            iconColor = 'text-success';
            bgColor = 'bg-success/20';
            break;
        case 2:
            statusText = '良';
            statusColor = 'text-blue-500';
            iconColor = 'text-blue-500';
            bgColor = 'bg-blue-500/20';
            break;
        case 3:
            statusText = '轻度污染';
            statusColor = 'text-warning';
            iconColor = 'text-warning';
            bgColor = 'bg-warning/20';
            break;
        case 4:
            statusText = '中度污染';
            statusColor = 'text-orange-500';
            iconColor = 'text-orange-500';
            bgColor = 'bg-orange-500/20';
            break;
        case 5:
            statusText = '重度污染';
            statusColor = 'text-danger';
            iconColor = 'text-danger';
            bgColor = 'bg-danger/20';
            break;
        default:
            statusText = '未知';
            statusColor = 'text-gray-500';
            iconColor = 'text-gray-500';
            bgColor = 'bg-gray-100';
    }
    
    aqiStatus